<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of CustomsfGuardValidatorUser
 *
 * @author vi-attik
 */
class CustomsfGuardValidatorUser extends sfGuardValidatorUser {

    public function configure($options = array(), $messages = array()) {
        //$this->addOption('username_field', 'username');
        $this->addOption('email_address_field', 'email_address');
        $this->addOption('password_field', 'password');
        $this->addOption('throw_global_error', false);

        $this->setMessage('invalid', 'The username and/or password is invalid.');
    }

    protected function doClean($values) {
        //$username = isset($values[$this->getOption('username_field')]) ? $values[$this->getOption('username_field')] : '';
        $email_address = isset($values[$this->getOption('email_address_field')]) ? $values[$this->getOption('email_address_field')] : '';
        $password = isset($values[$this->getOption('password_field')]) ? $values[$this->getOption('password_field')] : '';

        $allowEmail = sfConfig::get('app_sf_guard_plugin_allow_login_with_email', true);
        $method = $allowEmail ? 'retrieveByUsernameOrEmailAddress' : 'retrieveByUsername';

        // don't allow to sign in with an empty username
        //if ($username)
        if ($email_address) {
            if ($callable = sfConfig::get('app_sf_guard_plugin_retrieve_by_username_callable')) {
                $user = call_user_func_array($callable, array($username));
            } else {
                //$user = $this->getTable()->retrieveByUsername($username);
                $user = $this->getTable()->retrieveByEmailAddress($email_address);
            }
            // user exists?
            if ($user) {
                // password is ok?
                if ($user->getIsActive() && $user->checkPassword($password)) {
                    return array_merge($values, array('user' => $user));
                }
            }
        }

        if ($this->getOption('throw_global_error')) {
            throw new sfValidatorError($this, 'invalid');
        }

        throw new sfValidatorErrorSchema($this, array($this->getOption('username_field') => new sfValidatorError($this, 'invalid')));
    }

}

?>
